﻿Option Explicit On
Option Strict On

Imports System.IO

''' <summary>
''' Formulario login: Para validar al usuario que manipulará el programa
''' </summary>
''' <author>David Martínez</author>

Public Class Login
    'Usuario super Administrador
    Private Const User As String = "-1"
    Private Const Pass As String = "-1"
    Private _UsuarioTemp As Usuario
    Private AccesoBD As BBDD

    Private Sub btAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btAceptar.Click
        Dim entrar As Boolean = False

        If (User = tbUser.Text) And (Pass = tbPass.Text) Then
            entrar = True
        ElseIf ComprobarLogin() Then
            entrar = True
        Else
            MessageBox.Show("Login incorrecto")
        End If

        If entrar Then
            If cbRecordar.Checked = True Then
                Dim ficheroEscritura As New StreamWriter("user")
                ficheroEscritura.WriteLine(tbUser.Text)
                ficheroEscritura.WriteLine(tbPass.Text)
                ficheroEscritura.Close()
            Else
                File.Delete("user")
            End If
            Principal.Show()
            'Principal.UsuarioPrincipal = _UsuarioTemp
            Me.Visible = False
        End If

    End Sub

    Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If File.Exists("user") Then
            cbRecordar.Checked = True
            Dim ficheroLector As New StreamReader("user")
            tbUser.Text = ficheroLector.ReadLine
            tbPass.Text = ficheroLector.ReadLine
            ficheroLector.Close()
        End If
        _UsuarioTemp = New Usuario()
        AccesoBD = New BBDD()
    End Sub

    '----------------
    Private Function ComprobarLogin() As Boolean
        Dim resultado As Boolean = False
        _UsuarioTemp.DNI = tbUser.Text
        _UsuarioTemp.Password = tbPass.Text

        'comprobar login
        Try
            AccesoBD.Conectar()
            resultado = AccesoBD.Login(_UsuarioTemp)
            AccesoBD.Desconectar()

        Catch ex As Exception
            MsgBox("Hubo un error al conectar la base de datos: " & ex.Message)

        End Try

        Return resultado
    End Function


    Public ReadOnly Property UsuarioLogin As Usuario
        Get
            Return _UsuarioTemp
        End Get
    End Property
End Class